import Vue from 'vue'
import App from './App.vue'
////所有css集中放
import './src/all.css'
import './src/loginApp.css'

// import 'element-ui/lib/theme-chalk/index.css';
// import { Table,TableColumn,Scrollbar,DatePicker } from 'element-ui';
// Vue.use(Table);Vue.use(TableColumn);Vue.use(Scrollbar);Vue.use(DatePicker)

import LoadingBar from './mycomponents/loading-bar';
Vue.prototype.$Loading = LoadingBar;
import jquery from 'jquery';
Vue.prototype.$jq=jquery;//添加入vue原型链
import echarts from "echarts";
Vue.prototype.$echarts=echarts;
import Antd from 'ant-design-vue';
import 'ant-design-vue/dist/antd.css';
Vue.use(Antd);
// import Bus from './src/bus.js';
Vue.prototype.$Bus=new Vue();
// import upload from "./src/upload.js";
// Vue.prototype.$upload=upload;//添加入vue原型链




// var PindexedDB =new Promise((resolve ) => {
//   var request = window.indexedDB.open('xzqh', 1.0);
//     request.onerror = (event)=> {
//       resolve(false)
//     };
//     request.onsuccess =  (event)=> {
//       Vue.prototype.$indexedDB=request.result;
//       resolve(true)
//     };
//     request.onupgradeneeded = (event)=> {
//         Vue.prototype.$indexedDB  = event.target.result;
//         if (!Vue.prototype.$indexedDB.objectStoreNames.contains('user')) {//判断是否存在
//           Vue.prototype.$indexedDB.createObjectStore('user', { keyPath: 'name' }); //自动生成主键{ autoIncrement: true }
//         }
//         resolve(true)
//     }
// });
Vue.prototype.$geoserver = window.Glod.geoserver;
Vue.prototype.$geoserver_workspace = `${window.Glod.geoserver}${window.Glod.workspace?window.Glod.workspace+"/":""}`
Vue.prototype.$geoserver_wms = `${Vue.prototype.$geoserver_workspace}wms?`
Vue.prototype.$geoserver_wfs = `${Vue.prototype.$geoserver_workspace}wfs?`
import axios from "axios";
axios.defaults.baseURL = window.Glod.baseUrl+"xzqh"; 
axios.interceptors.request.use(
  config => {
    config.headers = {
      "Content-Type": " application/json"
    };
    if (config.auth=='true' && store.state.user.token) {
      config.headers.Authorization = store.state.user.token;
      delete config.auth
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);
axios.interceptors.response.use(
  (response)=> {
    if(response.headers && response.headers.authorization ){
      //Vue.prototype.$user.set_token(response.headers.authorization)
    }
    return response;
  },
  (error)=> {
    return Promise.reject(error);
  }
);
Vue.prototype.$axios = axios;

Vue.mixin({
    data() {
      return {
        public_images: process.env.BASE_URL+"images/",


        


        
    
    
      }
    },
    methods:{
      axios_get(url,qs={},auth=false){
        return this.axios_get_post(url,qs,auth,"get")
      },
      axios_post(url,qs={},auth=false){
        return this.axios_get_post(url,qs,auth,"post")
      },
      axios_get_post(url,qs={},auth=false,type="get"){
        return new Promise((resolve)=>{
          let config={}
          if(auth==true){config.auth='true'}
          let axios_then=undefined
          if(type=="get"){
            config={ params: qs}
            axios_then=this.$axios.get(url,config) 
          }
          else if(type=="post"){
            axios_then=this.$axios.post(url,qs,config) 
          }
          axios_then.then(res => {
            this.axios_get_post_back(res,resolve)
          }).catch((error)=>{
            resolve(false)
            this.$message.error(`search from server error.${error.message}`)
          })
        })
      },
      axios_get_post_back(res,resolve){
        let BackData=res.data
        if(BackData){
          if(BackData.features){
            resolve(BackData.features)
          }
          else if (BackData.status == true) {
            resolve(BackData.result)
          }
          else{
            resolve(false)
            this.$message.error(`${BackData.message}`)
          }
        }
        else{
          resolve(false)
        }
      },
      set_Geo_Layer_Name(_Year){
        let cite_name="";
        if(_Year==2019){
          cite_name=`cite:xzqh`
        }
        else if(_Year>=2022){
          cite_name=`cite:xzqh_${_Year}`
        }
        this.$store.state.Geo_Layer_Name=cite_name
      },


      GetLastRoute(routepath,num=0){
        let path=routepath.split('/')
        path=path[path.length-1-num]
        return path;
      },
      read_user(key="admin",StoreName='user'){
        return new Promise((resolve ) => {
            let transaction = this.$indexedDB.transaction([StoreName]);
            let objectStore = transaction.objectStore(StoreName);
            let request = objectStore.get(key);
            request.onerror = (event)=>{
                resolve(false);
            };
            request.onsuccess = (event)=> {
                if (request.result) {
                    resolve(request.result.value);
                } else {
                    resolve(false);
                }
            };
        });
      },
      write_user(value,key="admin",StoreName='user'){
        return new Promise((resolve) => {
            let store=this.$indexedDB.transaction([StoreName], 'readwrite').objectStore(StoreName);
            store.delete(key)
            let request = store.add({ name: key, value: value });
            request.onsuccess = (event)=> {
                resolve(true);
            };
            request.onerror = (event)=>{
                resolve(false);
            }
        });
      },
      check_logined_ajax(value){
        return new Promise((resolve ) => {
         
            $.ajax({
                type: "post",
                url: window.Glod.ajax+'xzqh/getuser',
                dataType: "json",
                async: true,
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("Authorization", value);
                },
                success: data => {
                    if(data.status==true){
                        resolve(data.result);
                    }
                    else{
                        resolve(false)
                    }
                },
                error: data => {
                   resolve(false)
                }
            });
        });
      },
      search_poi(searchtext,page=1,placeTypeCode=''){
        let that=this;
        // let ajaxSet={
        //   type:"post",
        //   async:true,
        //   url:'https://dmfw.mca.gov.cn/9095/stname/list?',
        //   data:
        // $.ajax(ajaxSet)
        return new Promise((resolve) => {
          this.axios_post('https://dmfw.mca.gov.cn/9095/stname/list?',{
            type: "place",
            stName: searchtext,
            code: "15",
            page: page,
            size: 10,
            placeTypeCode: placeTypeCode,
            placeTypeCodeLen: 0,
            code: 15,
            adminCodeLen: 2,
            searchType: '模糊',
            year:2018
          }).then(databack => {
            if(databack && databack !='HELLO ROBOT'){
              let result = databack
              var str2 = that.decryptByDES(result.substring(0, result.length - 6), that.getKey(result.substring(result.length - 6, result.length)));
              resolve(str2);
            }
            else{
              resolve(false)
            }
          })
        },error=>{
          resolve(false)
        });
      },
      search_poi_detail(id){
        let that=this;
        return new Promise((resolve) => {
          this.axios_post('https://dmfw.mca.gov.cn/9095/stname/details?',{
            "type": "place", 
            "id": id,
          }).then(databack => {
              if (databack) {
                  let result = databack
                  let active_result_details = that.decryptByDES(result.substring(0, result.length - 6),that.getKey(result.substring(result.length - 6, result.length)));
                  resolve(active_result_details);
              }
              else{
                resolve(false)
              }
          });
        });
      },
      search_poi_pics(palceCode,name,_year=2018){
        return new Promise((resolve) => {
          this.axios_post('https://dmfw.mca.gov.cn/place/photos.html?',{
            placeCode: palceCode,
            year:_year,
            name:name
         }).then(databack => {
              if (databack) {
                  resolve(databack);
              }
              else{
                resolve(false)
              }
          });
        });
      },
      decryptByDES(ciphertext, key) {
        var keyHex = CryptoJS.enc.Utf8.parse(key);
        var decrypted = CryptoJS.DES.decrypt({
            ciphertext: CryptoJS.enc.Base64.parse(ciphertext)
        }, keyHex, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.ZeroPadding
        });
        var data = decrypted.toString(CryptoJS.enc.Utf8);
        var lastNum = data.lastIndexOf("}");
        data = JSON.parse(data.substring(0, lastNum + 1));
        return data;
      },
      getKey: function (str) {
        let ajaxSet={
            type:"post",
            async:false,
            url:'https://dmfw.mca.gov.cn/9095/stname/keys/get.html',
            data:{
                "code": str,
            }
        }
        let key=''
        ajaxSet.success=(data)=> {
            key=data;
        }
        $.ajax(ajaxSet)
        if (key) {
            return key;
        }
      },
      GetPropFunc(regionid,_year,pre=false){
        return new Promise((resolve ) => {
          let data={}
          if(pre){
            data.precode=regionid
          }
          else{
            data.code=regionid
          }
          if(_year){
            data.year=_year
          }
          else{
            data.year=this.$store.state.Select_Year
          }
          this.axios_get("get_props?",data).then(databack=>{
            resolve(databack);
          });
        });
      },
      Get_TDTlayers(){
        let Groupvec=new ol.layer.Group({
            layers:[
                new ol.layer.Tile({
                    source: new ol.source.XYZ({
                        // url: "https://t{0-7}.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=b4a8d92e2c4a1ec59beead8cf44d4ecb"
                        url:"https://nmgwxyy.cn/alatan/services/ogc/wmts?layer=tianditu_vec_w&style=default&tilematrixset=w&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image%2Fpng&TileMatrix={z}&TileCol={x}&TileRow={y}"
                    })
                }),
                new ol.layer.Tile({
                    source: new ol.source.XYZ({
                        // url: "https://t{0-7}.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=b4a8d92e2c4a1ec59beead8cf44d4ecb"
                        url: "https://nmgwxyy.cn/alatan/services/ogc/wmts?layer=tianditu_cia_w&style=default&tilematrixset=w&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image%2Fpng&TileMatrix={z}&TileCol={x}&TileRow={y}"
                    })
                }),
            ],
            visible:false,
        })
        let Groupimg=new ol.layer.Group({
            layers:[
                new ol.layer.Tile({
                    source: new ol.source.XYZ({
                        url:"https://nmgwxyy.cn/alatan/services/ogc/wmts?layer=google_yx_title&style=default&tilematrixset=cc&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image%2Fpng&TileMatrix={z}&TileCol={x}&TileRow={y}"
                    })
                }),
                new ol.layer.Tile({
                    source: new ol.source.XYZ({
                        url: "https://nmgwxyy.cn/alatan/services/ogc/wmts?layer=tianditu_cia_w&style=default&tilematrixset=w&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image%2Fpng&TileMatrix={z}&TileCol={x}&TileRow={y}"
                    })
                }),
    
            ],
            visible:false,
        })
        return [Groupvec,Groupimg]
      },
      Getprop_detailsFunc(regionid){
        return new Promise((resolve ) => {
          this.axios_get(window.Glod.ajax+"xzqh/search_prop_details?",{
            code: regionid
        }).then(databack=>{
            resolve(databack);
          });
        });
      },
      getpic_img(value,item) {
        return `https://dmfw.mca.gov.cn/place/photos/download.html?compress=true&placeCode=${item.placeCode}&fileName=${value.trim()}&year=${item.year}`
      },
    },
  })
Vue.config.productionTip = false
Vue.config.silent = true
router.afterEach((to, from) => {
  if(VueApp){
    VueApp.$Loading.finish();
    let path=VueApp.GetLastRoute(to.path);
    if(VueApp.$first_update_active_path){ }
    else{
      VueApp.$first_update_active_path=path
    }
    //Bus.$emit('update_active',path);//第一次渲染时 还没有加载刷新页面 只有在window.onload中执行
    //Bus.$emit('update_activeIndex');
  }
})

import store from "./src/store.js";
import router from './src/router'
var VueApp=new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app')
router.beforeEach(async (to, from, next) => {
  VueApp.$Loading.start();
  //await PindexedDB;
  // if(VueApp){
  //   VueApp.$Loading.start();
  // }
  // if(to.meta && to.meta.requireAuth===true){
  //   let Authed=false
  //   let Auth=await VueApp.read_user();
  //   if(Auth){
  //     Authed=await VueApp.check_logined_ajax(Auth);
  //   }
  //   if(Authed){
  //     next()
  //   }
  //   else{
  //     next({path:'/home'})
  //   }
	// }else{
	// 	next()
  // }
  next()
})
window.onload=function(){ //只执行一次 
  if(VueApp.$first_update_active_path){
    //Bus.$emit('update_active',VueApp.$first_update_active_path);
    //Bus.$emit('update_activeIndex');
  }
  if(VueApp.$indexedDB){
    //Bus.$emit('ckeckLogin');
  }
}



